<template>
  <div class="paper-edit">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="160px"
        style="max-width: 600px; margin: 0 auto"
      >
        <el-form-item label="试卷名称" prop="name">
          <el-input v-model="form.name" maxlength="100" placeholder="请输入试卷名称" />
        </el-form-item>

        <el-form-item label="年级" prop="level">
          <el-select v-model="form.level" placeholder="请选择年级">
            <el-option
              v-for="(label, value) in levelMap"
              :key="value"
              :label="label"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科">
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="试卷类型" prop="paperType">
          <el-select v-model="form.paperType" placeholder="请选择试卷类型">
            <el-option label="固定试卷" :value="1" />
            <el-option label="限时试卷" :value="4" />
            <el-option label="任务试卷" :value="6" />
          </el-select>
        </el-form-item>

        <el-form-item label="建议考试时间(分钟)" prop="suggestTime">
          <el-input-number v-model="form.suggestTime" :min="1" :max="300" />
        </el-form-item>

        <el-form-item v-if="form.paperType === 4" label="考试限制时间" prop="limitDateTime">
          <el-date-picker
            v-model="form.limitDateTime"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item v-if="form.paperType === 6" label="任务开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择任务开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <!-- 标题列表 -->
        <div v-for="(title, index) in titleList" :key="title.id" class="title-item">
          <el-form-item :label="`标题${index + 1}`" :prop="`titles.${index}.name`">
            <el-input
              v-model="title.name"
              placeholder="请输入标题名称"
              style="width: 200px; margin-right: 10px"
            />
            <el-link type="primary" style="margin-right: 10px" @click="handleAddQuestion(title.id)">
              添加题目
            </el-link>
            <el-link type="danger" @click="handleDeleteTitle(index)">删除</el-link>
          </el-form-item>

          <!-- 显示该标题下的题目 -->
          <el-card v-if="title.questions.length > 0" class="question-card" style="margin-top: 10px">
            <div
              v-for="(question, qIndex) in title.questions"
              :key="question.id"
              class="question-item"
            >
              <div class="question-content">
                <div class="question-title">
                  <span class="question-number">第{{ qIndex + 1 }}题：</span>
                  <span>{{ question.title || question.shortTitle }}</span>
                </div>
                <div v-if="question.items && question.items.length > 0" class="question-options">
                  {{ formatQuestionOptions(question) }}
                </div>
              </div>
              <div class="question-actions">
                <el-link type="danger" @click="handleRemoveQuestion(title.id, question.id)">
                  移除
                </el-link>
              </div>
            </div>
          </el-card>
        </div>

        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交</el-button>
          <el-button :disabled="loading" @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAddTitle">添加标题</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 添加题目对话框 -->
    <el-dialog v-model="questionDialogVisible" width="80%">
      <div class="search-controls">
        <span class="search-label">题目ID：</span>
        <el-input
          v-model="questionSearch.id"
          placeholder="题目ID"
          style="width: 150px; margin-right: 10px"
        />
        <span class="search-label">题型：</span>
        <el-select
          v-model="questionSearch.type"
          placeholder="题型"
          style="width: 120px; margin-right: 10px"
          clearable
        >
          <el-option label="单选题" :value="1" />
          <el-option label="多选题" :value="2" />
          <el-option label="判断题" :value="3" />
          <el-option label="填空题" :value="4" />
          <el-option label="简答题" :value="5" />
        </el-select>
        <el-button type="primary" @click="handleSearchQuestions">搜索</el-button>
      </div>

      <el-table :data="questionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="questionType" label="题型" width="100">
          <template #default="scope">
            {{ getQuestionTypeText(scope.row.questionType) }}
          </template>
        </el-table-column>
        <el-table-column prop="shortTitle" label="题干" />
      </el-table>

      <el-pagination
        v-model:current-page="questionPagination.current"
        v-model:page-size="questionPagination.size"
        :total="questionPagination.total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="questionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmAddQuestions">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import UserAPI from "@/api/system/user.api";
import { ElMessage } from "element-plus";

interface SubjectType {
  id: number;
  name: string;
}

interface TitleType {
  id: number;
  name: string;
  questions: QuestionType[];
}

interface QuestionType {
  id: number;
  questionType: number;
  shortTitle: string;
  score: string;
  difficult?: number;
  status?: number;
  subjectId?: number;
  createTime?: string;
  createUser?: number;
  correct?: string;
  analyzeTextContentId?: any;
  textContentId?: any;
  title?: string;
  items?: Array<{
    prefix: string;
    content: string;
    score?: any;
    itemUuid?: any;
  }>;
  correctArray?: any;
  analyze?: string;
  gradeLevel?: number;
  itemOrder?: any;
}

// 年级映射：1-6 小学，7-9 初中，10-12 高中
const levelMap: Record<number, string> = {
  1: "一年级",
  2: "二年级",
  3: "三年级",
  4: "四年级",
  5: "五年级",
  6: "六年级",
  7: "初一",
  8: "初二",
  9: "初三",
  10: "高一",
  11: "高二",
  12: "高三",
};

const route = useRoute();
const router = useRouter();
const formRef = ref();
const subjectList = ref<SubjectType[]>([]);
const titleList = computed(() => form.titles);
const loading = ref(false);
const isEdit = computed(() => !!route.query.id);

// 题目对话框相关
const questionDialogVisible = ref(false);
const questionList = ref<QuestionType[]>([]);
const selectedQuestions = ref<QuestionType[]>([]);
const currentTitleId = ref<number | null>(null);
const questionSearch = reactive({
  id: "",
  type: undefined as number | undefined,
});
const questionPagination = reactive({
  current: 1,
  size: 10,
  total: 0,
});

const form = reactive({
  id: null as number | null,
  name: "",
  level: undefined as number | undefined,
  subjectId: undefined as number | undefined,
  paperType: 1 as number,
  suggestTime: 60,
  limitDateTime: [] as string[],
  startTime: "" as string,
  endTime: "" as string,
  titles: [] as TitleType[],
});

const rules = computed(() => ({
  name: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
  level: [{ required: true, message: "请选择年级", trigger: "change" }],
  subjectId: [{ required: true, message: "请选择学科", trigger: "change" }],
  paperType: [{ required: true, message: "请选择试卷类型", trigger: "change" }],
  suggestTime: [{ required: true, message: "请输入建议考试时间", trigger: "blur" }],
  limitDateTime:
    form.paperType === 4
      ? [{ required: true, message: "请选择考试限制时间", trigger: "change" }]
      : [],
}));

// 获取学科列表
function getSubjectList() {
  UserAPI.getSubjectList()
    .then((data: any) => {
      subjectList.value = data || [];
    })
    .catch(() => {
      ElMessage.error("获取学科列表失败");
    });
}

// 根据年级获取学科列表
function getSubjectListByLevel(level: number) {
  UserAPI.getSubjectPage({ level, pageIndex: 1, pageSize: 1000 })
    .then((data: any) => {
      subjectList.value = data.list || [];
    })
    .catch(() => {
      ElMessage.error("获取学科列表失败");
      subjectList.value = [];
    });
}

// 获取试卷详情
async function fetchDetail(id: number) {
  loading.value = true;
  try {
    const res: any = await UserAPI.getPaperDetail(id);
    const data = res;

    if (data) {
      form.id = data.id ?? id;
      form.name = data.name ?? "";
      form.level = data.level;
      form.subjectId = data.subjectId;
      form.paperType = data.paperType ?? 1;
      form.suggestTime = data.suggestTime ?? 60;
      form.limitDateTime = data.limitDateTime || [];
      form.startTime = data.startTime ?? "";
      form.endTime = data.endTime ?? "";

      // 处理标题和题目信息
      form.titles =
        data.titleItems?.map((titleItem: any, index: number) => ({
          id: Date.now() + index, // 生成唯一id
          name: titleItem.name || "",
          questions:
            titleItem.questionItems?.map((q: any) => ({
              id: q.id,
              questionType: q.questionType,
              shortTitle: q.title ? q.title.replace(/<[^>]*>/g, "") : "",
              title: q.title || "",
              score: q.score || "0",
              difficult: q.difficult || 3,
              subjectId: q.subjectId,
              correct: q.correct || "",
              analyze: q.analyze || "",
              gradeLevel: q.gradeLevel,
              items: q.items || [],
              correctArray: q.correctArray,
              itemOrder: q.itemOrder,
            })) || [],
        })) || [];
    }
  } catch {
    ElMessage.error("获取试卷详情失败");
  } finally {
    loading.value = false;
  }
}

function handleSubmit() {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    loading.value = true;

    const payload: any = {
      name: form.name,
      level: form.level, // 这里直接取form.level，确保与选择一致
      subjectId: form.subjectId,
      paperType: form.paperType,
      suggestTime: form.suggestTime,
      limitDateTime: form.limitDateTime || null,
      titleItems: form.titles.map((title, _titleIndex) => ({
        name: title.name,
        questionItems: title.questions.map((q, qIndex) => ({
          id: q.id,
          questionType: q.questionType,
          subjectId: q.subjectId || form.subjectId,
          title: q.title || q.shortTitle,
          gradeLevel: form.level, // 始终与form.level保持一致
          items: q.items || [],
          analyze: q.analyze || "",
          correctArray: q.correctArray || [],
          correct: q.correct || "",
          score: q.score || "0",
          difficult: q.difficult || 3,
          itemOrder: qIndex + 1,
        })),
      })),
      score: form.titles.reduce(
        (total, title) =>
          total + title.questions.reduce((sum, q) => sum + (Number(q.score) || 0), 0),
        0
      ),
    };

    // 如果是编辑，添加id字段
    if (isEdit.value && form.id) {
      payload.id = form.id;
    }

    UserAPI.editPaper(payload)
      .then(() => {
        ElMessage.success(isEdit.value ? "编辑成功" : "添加成功");
        router.back();
      })
      .catch(() => {
        ElMessage.error(isEdit.value ? "编辑失败" : "添加失败");
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

function handleReset() {
  if (isEdit.value && form.id) {
    fetchDetail(form.id);
  } else {
    Object.assign(form, {
      id: null,
      name: "",
      level: undefined,
      subjectId: undefined,
      paperType: 1,
      suggestTime: 60,
      limitDateTime: [],
      startTime: "",
      endTime: "",
      titles: [],
    });
  }
}

// 标题管理方法
function handleAddTitle() {
  const newTitle: TitleType = {
    id: Date.now(),
    name: "",
    questions: [],
  };
  form.titles.push(newTitle);
}

function handleDeleteTitle(index: number) {
  form.titles.splice(index, 1);
}

function handleAddQuestion(titleId: number) {
  currentTitleId.value = titleId;
  questionDialogVisible.value = true;
  // 重置搜索条件
  Object.assign(questionSearch, {
    id: "",
    type: undefined,
  });
  // 加载题目列表
  getQuestionList();
}

// 题目管理方法
function getQuestionList() {
  const payload: any = {
    pageIndex: questionPagination.current,
    pageSize: questionPagination.size,
  };

  // 如果有搜索条件，添加到 payload 中
  if (questionSearch.id) {
    payload.id = Number(questionSearch.id);
  }
  if (questionSearch.type) {
    payload.questionType = questionSearch.type;
  }

  UserAPI.getQuestionPage(payload)
    .then((res: any) => {
      questionList.value = res.list || [];
      questionPagination.total = res.total || 0;
    })
    .catch(() => {
      ElMessage.error("获取题目列表失败");
      questionList.value = [];
      questionPagination.total = 0;
    });
}

function handleSearchQuestions() {
  // 重置到第一页
  questionPagination.current = 1;
  getQuestionList();
}

function handleSelectionChange(selection: QuestionType[]) {
  selectedQuestions.value = selection;
}

function getQuestionTypeText(type: number): string {
  const typeMap: Record<number, string> = {
    1: "单选题",
    2: "多选题",
    3: "判断题",
    4: "填空题",
    5: "简答题",
  };
  return typeMap[type] || "未知";
}

// 格式化答案选项
function formatQuestionOptions(question: QuestionType): string {
  if (!question.items || question.items.length === 0) {
    return "";
  }

  const options = question.items.map((item) => item.content).join(" ");
  return `（${options}）`;
}

function handleSizeChange(size: number) {
  questionPagination.size = size;
  questionPagination.current = 1; // 重置到第一页
  getQuestionList();
}

function handleCurrentChange(current: number) {
  questionPagination.current = current;
  getQuestionList();
}

async function handleConfirmAddQuestions() {
  // 将选中的题目添加到当前标题中
  const currentTitle = form.titles.find((title) => title.id === currentTitleId.value);
  if (currentTitle && selectedQuestions.value.length > 0) {
    try {
      // 并发获取所有选中题目的详细信息
      const detailPromises = selectedQuestions.value.map((question) =>
        UserAPI.getQuestionDetail(question.id)
      );
      const details = await Promise.all(detailPromises);

      selectedQuestions.value.forEach((question, index) => {
        if (!currentTitle.questions.find((q) => q.id === question.id)) {
          const detail: any = details[index];
          // 合并基本信息和详细信息
          const fullQuestion = {
            ...question,
            ...detail,
            // 提取纯文本标题（去掉HTML标签）
            title: detail.title ? detail.title.replace(/<[^>]*>/g, "") : question.shortTitle,
          };
          currentTitle.questions.push(fullQuestion);
        }
      });
    } catch {
      ElMessage.error("获取题目详情失败");
      // 如果获取详情失败，仍添加基本信息
      selectedQuestions.value.forEach((question) => {
        if (!currentTitle.questions.find((q) => q.id === question.id)) {
          currentTitle.questions.push({ ...question });
        }
      });
    }
  }
  questionDialogVisible.value = false;
  selectedQuestions.value = [];
}

function handleRemoveQuestion(titleId: number, questionId: number) {
  const title = form.titles.find((t) => t.id === titleId);
  if (title) {
    const questionIndex = title.questions.findIndex((q) => q.id === questionId);
    if (questionIndex > -1) {
      title.questions.splice(questionIndex, 1);
    }
  }
}

onMounted(() => {
  getSubjectList();

  const id = Number(route.query.id);
  if (id) {
    form.id = id;
    fetchDetail(id);
  }
});

// 监听年级变化，动态获取学科列表
watch(
  () => form.level,
  (newLevel) => {
    if (newLevel) {
      getSubjectListByLevel(newLevel);
    } else {
      subjectList.value = [];
    }
  }
);
</script>

<style scoped lang="scss">
.paper-edit {
  padding: 32px 0;
}

.title-item {
  padding: 16px;
  margin-bottom: 16px;

  :deep(.el-form-item__label) {
    width: 160px;
    text-align: right;
  }
}

.question-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  padding: 8px 0;
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }

  .question-content {
    flex: 1;

    .question-title {
      display: flex;
      align-items: baseline;
      margin-bottom: 4px;

      .question-number {
        flex-shrink: 0;
        min-width: 60px;
        margin-right: 8px;
      }
    }

    .question-options {
      margin-top: 4px;
      margin-left: 68px;
      font-size: 14px;
      color: var(--el-text-color-regular);
      /* 60px (题号宽度) + 8px (题号右边距) */
    }
  }

  .question-actions {
    flex-shrink: 0;
    margin-top: 4px;
    margin-left: 16px;
  }
}

.search-bar {
  display: flex;
  align-items: center;
}

.search-controls {
  display: flex;
  align-items: center;
  margin-bottom: 20px;

  :deep(.el-input),
  :deep(.el-select),
  :deep(.el-button) {
    height: 32px;
  }
}

.search-label {
  margin-right: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  white-space: nowrap;
}

:deep(.el-dialog) {
  --el-dialog-padding-primary: 20px;
}
</style>
